package com.bill.gaty.mfidelity.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.util.Log;

import com.bill.gaty.mfidelity.beans.translation.TranslationResponse;
import com.google.gson.Gson;

public class Translator {
	public static String Translation_API_URL="http://api.mymemory.translated.net/get";//?q=Hello World!&langpair=en|it";
@SuppressWarnings("deprecation")
public static String translate(String from,String to,String Message){
String urlPath=	(Translator.Translation_API_URL+"?q="+URLEncoder.encode(Message)+"&langpair="+from+"|"+to);
Log.i("urlPath",urlPath+"")	;
try {
		URL url=new URL(urlPath);
		BufferedReader r=new BufferedReader(new InputStreamReader( url.openStream()));
	StringBuilder sb=new StringBuilder();
	String ligne=null;
	while(null!=(ligne=r.readLine()))
		sb.append(ligne);
	ligne=sb.toString();
	Gson g=new Gson();
	TranslationResponse response=g.fromJson(ligne, TranslationResponse.class);

	Log.i("TranslationResponse",response.toString()+"")	;
	return response.getMostMatch().getTranslation();
} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		Log.e("MalformedURLException",e.getMessage()+"");
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		Log.e("IOException",e.getMessage()+"");
	}
catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	Log.e("IOException",e.getMessage()+"");
}
	
return Message;
}
public static TranslationResponse getTranslate(String from,String to,String Message){
	@SuppressWarnings("deprecation")
	String urlPath=	(Translator.Translation_API_URL+"?q="+URLEncoder.encode(Message)+"&langpair="+from+"|"+to);
	Log.i("urlPath",urlPath+"")	;
	try {
			URL url=new URL(urlPath);
			BufferedReader r=new BufferedReader(new InputStreamReader( url.openStream()));
		StringBuilder sb=new StringBuilder();
		String ligne=null;
		while(null!=(ligne=r.readLine()))
			sb.append(ligne);
		ligne=sb.toString();
		Gson g=new Gson();
		TranslationResponse response=g.fromJson(ligne, TranslationResponse.class);

		Log.i("TranslationResponse",response.toString()+"")	;
		return response;
	} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("MalformedURLException",e.getMessage()+"");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("IOException",e.getMessage()+"");
		}
	catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		Log.e("IOException",e.getMessage()+"");
	}
		
	return null;
	 
}
}
